from django.shortcuts import render, HttpResponse
from utils.serve import sms
from dvd1 import settings
from django import forms
from app import models
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError

import random

def send_msg(request):
    '''发送短信'''
    tid = request.GET.get('tq')
    temid = settings.SMS_TEMID.get(tid)
    if not temid:
        return HttpResponse('模板不存在')
    code = random.randrange(1000, 9000)
    res = sms.send_sms_single('132881127', temid, [code, ])
    if res['result'] == 0:
        return HttpResponse('成功')
    else:
        return HttpResponse(res['res'])
    pass

class RegisterModelForm(forms.ModelForm):

    phone_num = forms.CharField(
        label='手机号码',
        validators=[RegexValidator(r'^(1[3|4|5|6|7|8|9])\d{9}$', '手机号格式错误'), ]
    )
    password = forms.CharField(
        label='注册密码',
        widget=forms.PasswordInput()
    )
    repeat_pw = forms.CharField(
        label='重复密码',
        widget=forms.PasswordInput()
    )
    code = forms.CharField(
        label='验证码',
        widget=forms.TextInput()
    )

    class Meta:
        model = models.UserInfo
        fields = ['username', 'email', 'password', 'repeat_pw', 'phone_num', 'code']
        pass

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'
            field.widget.attrs['placeholder'] = '请输入%s'%(field.label,)


    pass


def register(request):
    form = RegisterModelForm()
    return render(request, 'app/register.html', {'form': form})